package com.ali.ttt.netty.common.domain;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Author : yuxl
 * @create 2024/7/8 10:19 AM
 */
@Slf4j
@Data
public class SessionMap {

    private static SessionMap singleInstance = new SessionMap();

    private ConcurrentHashMap<String, ServerSession> map =
            new ConcurrentHashMap<String, ServerSession>();

    public static SessionMap inst() {
        return singleInstance;
    }

    public void addSession( ServerSession s) {
        map.put(s.getSessionId(), s);
        log.info("客户端登录:host= " + s.getClient().getHost()
                + "prod=" + s.getClient().getProd()
                + "   在线总数: " + map.size());

    }

    /**
     * 根据用户id，获取session对象
     */
    public List<ServerSession> getSessionsBy(Client client) {
        List<ServerSession> list = map.values()
                .stream()
                .filter(s -> s.getClient().getHost().equals(client.getHost()))
                .filter(s -> s.getClient().getProd().equals(client.getProd()))
                .collect(Collectors.toList());
        return list;
    }

    public void removeSession(String sessionId) {
        if (!map.containsKey(sessionId)) {
            return;
        }
        ServerSession s = map.get(sessionId);
        map.remove(sessionId);
        log.info("客户端下线:host= " + s.getClient().getHost()
                + "prod=" + s.getClient().getProd()
                + "   在线总数: " + map.size());
    }

    public boolean hasLogin(Client client) {
        Iterator<Map.Entry<String, ServerSession>> it =
                map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, ServerSession> next = it.next();
            Client c = next.getValue().getClient();
            if (c.getHost().equals(client.getHost())
                    && c.getProd().equals(client.getProd())) {
                return true;
            }
        }

        return false;
    }

}
